package httpconnect;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zy on 2018/10/17.
 */
public class HttpMethod {
    /**
     * 发送https请求共用体
     */
    public static String sendPost(String url, String parame, Map<String, Object> paramsMap, File file) throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException {
        // 请求结果
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        URL realUrl;
        String method = "GET";
        HttpURLConnection conn;
        //查询地址
        String queryString = url;
        //请求参数获取
        String postpar = "";
        //字符串请求参数
        if (parame != null) {
            postpar = parame;
        }
        // map格式的请求参数
        if (paramsMap != null) {
            StringBuffer mstr = new StringBuffer();
            for (String str : paramsMap.keySet()) {
                String val = (String) paramsMap.get(str);
                try {
                    val = URLEncoder.encode(val, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                mstr.append(str + "=" + val + "&");
            }
            // 最终参数
            postpar = mstr.toString();
            int lasts = postpar.lastIndexOf("&");
            postpar = postpar.substring(0, lasts);
        }
        if (method.toUpperCase().equals("GET")) {
            queryString += "?" + postpar;
        }
        SSLSocketFactory ssf = BZX509TrustManager.getSSFactory();
        try {
            realUrl = new URL(queryString);
            conn = (HttpURLConnection) realUrl.openConnection();
            //conn.setSSLSocketFactory(ssf);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-type", "text/html; charset=UTF-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (method.toUpperCase().equals("POST")) {
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                out = new PrintWriter(conn.getOutputStream());
                out.print(postpar);
                out.flush();
            } else {
                conn.connect();
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            if (file != null) {
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
                os.write(result.toString().getBytes());
            }
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

}
